//% color="#FF6B35" iconWidth=50 iconHeight=40
namespace RC522 {
    
    //% block="RC522 Init with SDA pin [SDA_PIN] RST pin [RST_PIN] [MOSI][MISO][SCK]" blockType="command"

    //% SDA_PIN.shadow="dropdown" SDA_PIN.options="DIGITAL_PINS"
    //% RST_PIN.shadow="dropdown" RST_PIN.options="DIGITAL_PINS"
    export function RC522Init(parameter: any, block: any) {
        let sdaPin = parameter.SDA_PIN.code;
        let rstPin = parameter.RST_PIN.code;
        
        Generator.addInclude("MFRC522_lib", "#include <SPI.h>");
        Generator.addInclude("MFRC522_lib2", "#include \"MFRC522.h\"");
        Generator.addObject("MFRC522_init", "MFRC522", `mfrc522(${sdaPin}, ${rstPin});`);
        
        Generator.addSetup("MFRC522_setup", `SPI.begin();
  mfrc522.PCD_Init();`);
    }

    //% block="Is new card detected?" blockType="boolean"
    export function isNewCardDetected(parameter: any, block: any) {
        Generator.addCode([`mfrc522.MFRC522_IsNewCard(&mfrc522)`, Generator.ORDER_UNARY_POSTFIX]);
    }
           //% block="---"
    export function noteSep() {}
    //% block="Get card UID" blockType="reporter"
    export function getCardUID(parameter: any, block: any) {
        Generator.addCode([`mfrc522.MFRC522_ReadCardUID(&mfrc522)`, Generator.ORDER_UNARY_POSTFIX]);
    }
       //% block="---"
    export function noteSep1() {}

    //% block="Write data [DATA] to block [BLOCK]" blockType="command"
    //% DATA.shadow="string" DATA.defl="Hello RFID"
    //% BLOCK.shadow="number" BLOCK.defl="4"
    export function writeCard(parameter: any, block: any) {
        let data = parameter.DATA.code;
        let blockNum = parameter.BLOCK.code;
        
        Generator.addCode(`byte writeBuffer[16];
  memset(writeBuffer, 0, sizeof(writeBuffer));
  String dataStr = ${data};
  for (int i = 0; i < dataStr.length() && i < 16; i++) {
    writeBuffer[i] = dataStr[i];
  }`);
        Generator.addCode(`mfrc522.MFRC522_WriteCard(&mfrc522, ${blockNum}, writeBuffer, 16);`);
    }
      //% block="Read data from block [BLOCK]" blockType="command"
    //% BLOCK.shadow="number" BLOCK.defl="4"
    export function readCard(parameter: any, block: any) {
        let blockNum = parameter.BLOCK.code;
        Generator.addObject("byte_array", "byte", "mylist[16];");
        Generator.addCode(`mfrc522.MFRC522_ReadCard(&mfrc522, ${blockNum}, mylist, 16);`);
    }
    //% block="Read data" blockType="reporter"
    export function readCarddata(parameter: any, block: any) {
  
        Generator.addCode(`(char*)mylist`);
    }
    
      //% block="Read data" blockType="command"
    export function readCarddataloop(parameter: any, block: any) {
  
        Generator.addCode(`mfrc522.PICC_HaltA();
    mfrc522.PCD_StopCrypto1();`);
    }  

}
